package com.utils;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class ResultJson {
	/** 响应状态 ，100成功，200失败.默认是成功状态。json必定有参数 */
	private int status = 100;

	/** 具体数据。json必定有的参数 */
	private Object rows;

	/** 分页的页数，默认为-1，不分页。json可能有的参数 */
	private int total = -1;

	/** 响应消息。json可能有的参数 */
	private String message = null;

	Map<String, Object> jsonMap = new HashMap<String, Object>();

	public ResultJson() {
	}

	/**
	 * 只有数据的情况下默认是成功
	 * 
	 * @param rows
	 *            数据
	 */
	public ResultJson(Object rows) {
		this.status = 100;
		this.rows = rows;
	}

	/**
	 * @param status
	 *            状态
	 * @param rows
	 *            数据
	 */
	public ResultJson(int status, Object rows) {
		this.status = status;
		this.rows = rows;
	}

	/**
	 * @param status
	 *            状态
	 * @param rows
	 *            数据
	 * @param message
	 *            提示消息
	 */
	public ResultJson(int status, Object rows, String message) {
		this.status = status;
		this.rows = rows;
		this.message = message;
	}

	/**
	 * @param status
	 *            状态
	 * @param message
	 *            提示消息
	 */
	public ResultJson(int status, String message) {
		this.status = status;
		this.message = message;
	}

	/**
	 * @param status
	 *            状态
	 * @param total
	 *            分页总数
	 * @param rows
	 *            数据
	 * @param message
	 *            提示消息
	 */
	public ResultJson(int status, int total, Object rows, String message) {
		this.status = status;
		this.total = total;
		this.rows = rows;
		this.message = message;
	}

	// 获取最终Json数据
	public String getCommonJson() throws Exception {
		jsonMap.put("status", status);
		if (StringUtils.isNotBlank(message)) {
			jsonMap.put("message", message);
		}

		if (total > -1)
			jsonMap.put("total", total);
		jsonMap.put("rows", rows == null ? "" : rows);

		return this.returnJson(jsonMap);
	}

	public static String returnJson(Object object) throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		StringWriter stringWriter = new StringWriter();
		objectMapper.writeValue(stringWriter, object);
		return stringWriter.toString();
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public Object getRows() {
		return rows;
	}

	public void setRows(Object rows) {
		this.rows = rows;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

}